<template>
  <div class="card" style="max-width:420px;margin:40px auto;padding:20px;">
    <h2 style="margin-top:0;">登录</h2>
    <form class="space-y" @submit.prevent="submit">
      <div class="space-y">
        <label class="muted">用户名</label>
        <input class="input" v-model="username" required />
      </div>
      <div class="space-y">
        <label class="muted">密码</label>
        <input class="input" type="password" v-model="password" required />
      </div>
      <button class="btn" type="submit">登录</button>
      <div style="color:#ef4444;" v-if="error">{{ error }}</div>
    </form>
  </div>
</template>

<script>
export default {
  data(){ return { username:'', password:'', error:'' } },
  methods:{
    async submit(){
      this.error = ''
      const res = await fetch('/api/v1/auth/login', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ username:this.username, password:this.password }) })
      if(res.ok){
        const user = await res.json()
        localStorage.setItem('user', JSON.stringify(user))
        // 触发storage事件，通知其他组件更新用户状态
        window.dispatchEvent(new Event('storage'))
        location.hash = '#/'
      } else {
        this.error = '账号或密码错误'
      }
    }
  }
}
</script>


